package net.jcip.examples.vehicles;

import net.jcip.examples.vehicles.point.MutablePoint;
import net.jcip.examples.vehicles.point.Point;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class MonitorVehicleTracker {

    private final Map<String, Point> locations;

    public MonitorVehicleTracker(Map<String, Point> data) {
        locations = deepCopy(data);
    }

    private Point safeGet(String name) {
        Point loc = locations.get(name);
        if (loc == null)
            throw new IllegalArgumentException("No such ID: " + name);
        return loc;
    }

    public synchronized Point getLocation(String name) {
        return new MutablePoint(safeGet(name));
    }

    public synchronized void setLocation(String name, Point point) {
        Point loc = safeGet(name);
        loc.setX(point.getX());
        loc.setY(point.getY());
    }

    public synchronized Map<String, Point> getLocations() {
        return deepCopy(locations);
    }

    private Map<String, Point> deepCopy(Map<String, Point> data) {
        Map<String, Point> copy = new HashMap<String, Point>();
        for (String id : data.keySet()) {
            Point point = locations.get(id);
            copy.put(id, new MutablePoint(point));
        }
        return Collections.unmodifiableMap(copy);
    }

}
